const app = getApp();
import { $wuxDialog, $wuxActionSheet } from "../../utils/wux/wux";
import login from "../../utils/login";
import fetch, { baseUrl, loginUrl, wssUrl, imgUrl } from "../../utils/fetch";

function GetRandomNum(Min, Max) {
  const Range = Max - Min;
  const Rand = Math.random();
  return (Min + Math.round(Rand * Range));
}

Page({
  data: {
    imgPath: ["../../images/Light.png", "../../images/Light-active.png"],
    socketOpen: false,
    socketOpenAgain: true,
    user: app.globalData.userInfo,
    userLove: false,
    indicatorDots: false,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    loverId: 0,
    lover: {},
    starer: [],
    linker: [],
    impress: [],
    notice: [],
    imgUrl,
    replyStatus: false,
    replyToUserNickName: '',
    replyToUserWxaId: 0,
    replyImpressId: 0,
    replyToUserId: 0,
    reply: '',
    config: {
      show: false
    },
    wxa: {},
    logo: "https://api.qingful.com/api/public/logo"
  },
  onLoad: function (options) {
    this.setData({
      loverId: options.id
    });
    console.log(options);
    wx.closeSocket();
  },
  onShow: function () {
    const that = this;
    login().then(res => {
      fetch(loginUrl, res).then(params => {

        wx.setStorageSync("token", params.data.data.token);

        that.setData({
          user: params.data.data.user
        });

        fetch('https://api.qingful.com/api/base/get_wxa_info').then(res => {
          this.setData({
            wxa: res.data.data
          });
          if (this.data.wxa.debug) {
            wx.setEnableDebug({
                enableDebug: true
            });
          }
        });

        wx.connectSocket({
          url: `${wssUrl}?Authorization=${params.data.data.token}&WxaToken=${params.data.data.watermark.appid}&loverId=${that.data.loverId || 1}`
        });

        wx.onSocketOpen(function (res) {
          console.log("连接服务器成功。");
          that.setData({ socketOpen: true });
        });

        wx.onSocketClose(function (res) {
          console.log('WebSocket 已关闭！');
          that.setData({ socketOpen: false });

          if (!that.data.socketOpenAgain) {
            return;
          }

          // 3s重连接
          const timeoutSocket = setTimeout(function () {
            console.log('WebSocket 重新尝试连接');
            if (that.data.socketOpen) {
              clearTimeout(timeoutSocket);
              return;
            }
            wx.connectSocket({
              url: `${wssUrl}?Authorization=${params.data.data.token}&WxaToken=${params.data.data.watermark.appid}&loverId=${that.data.loverId || 1}`
            });
          }, 3000);
        })

        wx.onSocketMessage(function (res) {
          // console.log('收到服务器内容：' + res.data);

          const json = JSON.parse(res.data);
          if (json.type == 'connection') {
            that.setData({
              lover: json.lover,
              starer: json.starer,
              linker: json.linker,
              impress: json.impress,
              config: json.config
            });

            for (let key in json.starer) {
              if (json.starer[key].user_id == that.data.user.id) {
                that.setData({
                  userLove: true
                });
              }
            }
            wx.hideNavigationBarLoading();
            return;
          }

          if (json.lover.id != that.data.lover.id) {
            return;
          }

          // 开始震动
          if (wx.vibrateLong){
            wx.vibrateLong({
              success: () => { },
              fail: (err) => {
                console.log(err);
              },
            });
          }

          if (json.type == 'star') {
            that.setData({
              starer: [].concat(that.data.starer, json.starer.user)
            });
            if (json.starer.user.id == that.data.user.id) {
              that.setData({
                userLove: true
              });
            }

            const notice = that.data.notice;
            notice.push({
              user: json.starer.user,
              content: `${json.starer.user.user_wxa.nickName}帮Ta点亮`,
              top: GetRandomNum(0, 200),
              time: GetRandomNum(20, 80),
              status: 1
            });

            that.setData({
              notice: notice
            });
          }

          if (json.type == 'link') {
            that.setData({
              linker: [].concat(that.data.linker, json.linker.user)
            });

            const notice = that.data.notice;
            notice.push({
              user: json.linker.user,
              content: `${json.linker.user.user_wxa.nickName}帮Ta牵线`,
              top: GetRandomNum(0, 200),
              time: GetRandomNum(20, 80),
              status: 1
            });

            that.setData({
              notice: notice
            });
          }

          if (json.type == 'impress') {
            that.setData({
              impress: [].concat(that.data.impress, json.impress)
            });

            const notice = that.data.notice;
            notice.push({
              user: {
                user_wxa: json.impress.user_wxa
              },
              content: `${json.impress.user_wxa.nickName}帮Ta印象 ${json.impress.content}`,
              top: GetRandomNum(0, 200),
              time: GetRandomNum(20, 80),
              status: 1
            });

            that.setData({
              notice: notice
            });
          }

          if (json.type == 'reply') {
            const impress = that.data.impress;
            let has = false;
            for (let key in impress) {
              if (json.impress.id == impress[key].id) {
                has = true;
                impress[key].reply.push(json.reply);
                that.setData({
                  impress: impress
                });
              }
            }
            if (!has) {
              impress.push(json.impress);
              that.setData({
                impress: impress
              });
            }

            const notice = that.data.notice;
            notice.push({
              user: {
                user_wxa: json.reply.from_user
              },
              content: `${json.reply.from_user.nickName}回复${json.reply.to_user.nickName} ${json.reply.content}`,
              top: GetRandomNum(0, 200),
              time: GetRandomNum(20, 80),
              status: 1
            });

            that.setData({
              notice: notice
            });
          }
        })
      })
    })
  },

  close: function (e) {
    const index = e.currentTarget.dataset.index;
    const notice = this.data.notice;
    notice[index].status = 0;
    this.setData({
      notice: notice
    });
  },
  star: function () {
    if (this.data.socketOpen) {
      wx.sendSocketMessage({
        data: JSON.stringify({
          type: 'star',
          user: this.data.user
        })
      });
    }
  },
  link: function () {

    const that = this;
    const hideSheet = $wuxActionSheet.show({
      theme: 'wx',
      titleText: '认识了这么多年，Ta还没有对象，帮Ta牵个线吧',
      style: 'background-color: transparent',
      buttons: [
        {
          text: '发送给朋友',
          openType: 'share'
        },
        {
          text: '发送到朋友圈'
        },
      ],
      buttonClicked(index, item) {
        if (index == 1) {

          const urls = [];
          if (that.data.lover.thumb && that.data.lover.thumb.length) {
            for (let key in that.data.lover.thumb) {
              urls.push(`${baseUrl}/api/public/thumb?loverId=${that.data.lover.id}&thumbId=${that.data.lover.thumb[key].id}`);
            }
          } else {
            urls.push(`${baseUrl}/api/public/thumb?loverId=${that.data.lover.id}`);
          }

          wx.previewImage({
            urls: urls
          });
        }
        return true
      },
    })
  },
  impress: function () {
    const that = this;
    $wuxDialog.prompt({
      content: '请输入您对Ta的印象，帮助Ta找到合适的对象',
      fieldtype: 'text',
      password: 0,
      defaultText: '',
      style: 'color: #fc466d',
      placeholder: '请输入...',
      onConfirm(e) {
        const value = that.data.$wux.dialog.prompt.response
        if (!value) {
          wx.showModal({
            content: '请输入您对Ta的印象，帮助Ta找到合适的对象',
            showCancel: false
          });
          return;
        }
        if (that.data.socketOpen) {
          wx.sendSocketMessage({
            data: JSON.stringify({
              type: 'impress',
              user: that.data.user,
              content: value
            })
          });
        }
      },
    })
  },
  onShareAppMessage: function (res) {
    const that = this;
    return {
      title: `小红娘帮Ta牵线，认识了${that.data.lover.name}这么多年，Ta还没有对象，我感到寝食难安。`,
      path: `/pages/index/index?id=${that.data.loverId || 1}`,
      success: function (res) {
        // 转发成功
        if (that.data.socketOpen) {
          wx.sendSocketMessage({
            data: JSON.stringify({
              type: 'link',
              user: that.data.user
            })
          });
        }
      },
      fail: function (res) {
        // 转发失败
      }
    }

  },
  find: function () {

    if (this.data.socketOpen) {
      this.setData({
        socketOpenAgain: false
      });
      wx.closeSocket();
    }

    wx.navigateTo({
      url: '/pages/product/product?show=true',
    })
  },
  reply: function (e) {
    const dataset = e.currentTarget.dataset;
    console.log(dataset);
    this.setData({
      replyStatus: true,
      replyToUserWxaId: dataset.to_user_wxa_id,
      replyToUserNickName: dataset.to_user_wxa_nickname,
      replyImpressId: dataset.id,
      replyToUserId: dataset.to_user_id
    })
  },
  bindReplyInput: function (e) {
    this.setData({
      reply: e.detail.value
    })
  },
  replySubmit: function (e) {

    if (this.data.socketOpen) {
      if (!this.data.reply || !this.data.replyImpressId || !this.data.replyToUserWxaId) {
        wx.showModal({
          content: '请输入要回复的内容',
          showCancel: false
        });
        return;
      }

      wx.sendSocketMessage({
        data: JSON.stringify({
          type: 'reply',
          user: this.data.user,
          content: this.data.reply,
          to_user_id: this.data.replyToUserId,
          to_user_wxa_id: this.data.replyToUserWxaId,
          impress_id: this.data.replyImpressId
        })
      });
    }

    this.setData({
      reply: ''
    });
    this.cancelReply();
  },
  cancelReply: function () {
    this.setData({
      replyToUserWxaId: 0,
      replyToUserNickName: '',
      replyStatus: false
    })
  },
  makePhoneCall: function () {
    wx.makePhoneCall({
      phoneNumber: this.data.config.tel //仅为示例，并非真实的电话号码
    });
  }
});